package com.lhframework.upload.uploader;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.OSSObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.InputStream;

/**
 * Created by lh on 2017/8/8.
 */
@Component
public class FileUploader {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Value("${oss.endpoint}")
    private String endpoint;

    @Value("${oss.accessKeyId}")
    private String accessKeyId;

    @Value("${oss.accessKeySecret}")
    private String accessKeySecret;

    @Value("${oss.bucketName}")
    private String bucketName;

    private OSSClient ossClient;

    public OSSClient getOssClient() {
        if (ossClient == null) {
            ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        }
        return ossClient;
    }

    public String upload(byte[] fileBytes, String fileName) {
        getOssClient().putObject(bucketName, fileName, new ByteArrayInputStream(fileBytes));
        String url = "http://" + bucketName + "." + endpoint + "/" + fileName;
        logger.info("文件上传（url：" + url + "）");
        return url;
    }

    public InputStream download(String fileName) {
        OSSObject ossObject = getOssClient().getObject(bucketName, fileName);
        logger.info("文件下载（bucketName：" + bucketName + "，fileName：" + fileName + "）");
        return ossObject.getObjectContent();
    }

    private void close() {
        getOssClient().shutdown();
    }

}
